<template>
  <px-dialog v-model="dialogTableVisible" :title="option.title" :width="900" draggable>
    <px-form
      ref="ruleFormRef"
      v-loading="loading"
      :model="ruleForm"
      :rules="rules"
      inline
      label-width="100px"
      class="demo-ruleForm"
      :size="formSize"
      status-icon
    >
      <px-row>
        <px-col v-if="option.eqpType === 'eqp'" :span="8">
          <px-form-item label="设备名称" prop="deviceName" required>
            <px-select
              v-model="deviceItem"
              filterable
              clearable
              remote
              placeholder="请输入设备名称"
              maxlength="50"
              :loading="searchLoading"
              :remote-method="remoteMethod"
              value-key="eqpId"
              :disabled="option.type === 'detail'"
              @change="deviceNameChange"
            >
              <px-option v-for="item in deviceOptions" :key="item.eqpId" :label="`${item.eqpName}(${item.eqpId})`" :value="item" />
            </px-select>
          </px-form-item>
        </px-col>
        <px-col v-for="item in baseDeviceProps" :key="item.prop" :span="8">
          <px-form-item :label="item.label" :prop="item.prop">
            <px-input v-if="item.prop === 'manageProperty'" :model-value="getManagePropertyMap(ruleForm[item.prop])" disabled />
            <px-input v-else v-model.trim="ruleForm[item.prop]" disabled />
          </px-form-item>
        </px-col>
        <px-col :span="8">
          <px-form-item class="attachLabel" label="设备附件名称" prop="deviceAttachName" :required="option.eqpType !== 'eqp'">
            <px-select
              v-model="deviceAttachItem"
              filterable
              clearable
              remote
              :allow-create="option.eqpType !== 'eqp'"
              placeholder="请选择设备附件名称"
              maxlength="40"
              :loading="searchLoading"
              :remote-method="attachRemoteMethod"
              value-key="eqpId"
              :disabled="option.type === 'detail'"
              @change="deviceNameAttachChange"
            >
              <px-option
                v-for="item in deviceAttachOptions"
                :key="item.eqpId"
                :label="item.eqpId ? `${item.eqpName}(${item.eqpId})` : `${item.eqpName}`"
                :value="item"
              />
            </px-select>
          </px-form-item>
        </px-col>
        <px-col :span="8">
          <px-form-item label="责任人" prop="person">
            <px-select-v2
              v-model="ruleForm.person"
              filterable
              clearable
              placeholder="请选择责任人"
              :options="personOptions"
              :disabled="option.type === 'detail'"
              @change="personChange"
            />
          </px-form-item>
        </px-col>
      </px-row>
      <px-form-item label="检验信息" prop="parameters" required>
        <CheckTable :disabled="option.type === 'detail'" :table-data="ruleForm.parameters" @update="updateParameters" />
      </px-form-item>
      <px-row class="mb-2">
        <px-col :span="8" :offset="2">
          <!-- <span style="width: 50px">周期</span> -->
          <px-form-item label="周期" prop="cycle" required>
            <px-input v-model.trim="ruleForm.cycle" :disabled="option.type === 'detail'">
              <template #append>天</template>
            </px-input>
          </px-form-item>
        </px-col>
        <px-col :span="8" :offset="2">
          <!-- <span style="width: 130px" class="mr-2">下次检验日期</span> -->
          <px-form-item label="下次检验日期" prop="nextVerifyDate">
            <px-date-picker v-model="ruleForm.nextVerifyDate" type="date" disabled />
          </px-form-item>
        </px-col>
        <px-col :span="7" :offset="3" class="custom-label flex-none">
          <span style="width: 120px">临期倒计时</span>
          <!-- <px-form-item label="临期倒计时" prop="countDown"> -->
          <px-input v-model.trim="ruleForm.countDown" disabled> <template #append>天</template></px-input>
          <!-- </px-form-item> -->
        </px-col>
        <px-col :span="8" :offset="2" class="custom-label">
          <span class="mr-2">第</span>
          <px-input v-model.trim="ruleForm.reminder" class="mr-2" :disabled="option.type === 'detail'" />
          <span style="width: 110px">天邮件提醒</span>
        </px-col>
      </px-row>
      <px-form-item label="附件上传" prop="files">
        <ReUploadFile v-model="ruleForm.files" :disabled="option.type === 'detail'" isPreview :limit="50" />
        <!-- <FileUpload v-else fileType="view" isPreview :fileList="fileList" /> -->
      </px-form-item>
    </px-form>
    <template #footer>
      <span class="dialog-footer">
        <px-button @click="cancelHandler">取消</px-button>
        <px-button v-if="option.type != 'detail'" type="primary" :loading="loading" @click="submitHandler"> 确认 </px-button>
      </span>
    </template>
  </px-dialog>
</template>
<script setup lang="ts">
defineOptions({
  name: "GAS_TASK_MONITORINGMANAGE_EQP_CHECKOUT_ADD"
});

import { ref, reactive, onMounted, watchEffect } from "vue";
import type { FormInstance, FormRules } from "px-ui";
import { useThrottleFn } from "@vueuse/core";
import { throttleDelay as delay } from "@/utils/constant";
import { ReUploadFile } from "./uploadTable";
import { queryEquipLedger } from "@/api/equip/archive";
import { getEmployeeIdAndName } from "@/utils/pengxi";
import CheckTable from "./checkTable.vue";
import { insertVerifyReport, updateVerifyReport, queryVerifyReportDetail } from "@/api/verifyReport";
import dayjs from "dayjs";
import { PxMessage } from "px-ui";

interface Props {
  // 科室
  className: string;
  option: {
    title: string;
    // 设备 or 设备附件 or 设备附件列表可能没有设备code 查详情需要使用id
    eqpType: "eqp" | "attachment" | "attachCustom";
    // 弹框类型 add 新增   edit 编辑 detail 详情
    type: "add" | "edit" | "detail";
    data: Record<string, any>;
  };
}

const props = withDefaults(defineProps<Props>(), {});
const dialogTableVisible = defineModel({ type: Boolean, default: false });

const loading = ref(false);
interface RuleForm {
  deviceName: string;
  eqpStatus: string;
  deviceStatus: string;
  deviceCode: string;
  manageProperty: string;
  deviceAttachName: string;
  deviceAttachCode: string;
  person: string;
  personId: number;
  nextVerifyDate: any;
  reminder: number;
  cycle: string;
  countDown: number;
  parameters: Array<any>;
  files: Array<string>;
  [propName: string]: any;
}

const formSize = ref("default");
const ruleFormRef = ref<InstanceType<typeof FormInstance>>();
const ruleForm = reactive<RuleForm>({
  deviceName: "",
  eqpStatus: "",
  deviceStatus: "",
  deviceCode: "",
  manageProperty: "",
  deviceAttachName: "",
  deviceAttachCode: "",
  person: "",
  personId: null,
  nextVerifyDate: "",
  reminder: 30,
  cycle: "",
  countDown: null,
  files: [],
  parameters: [],
  className: props.className
});

// 计算下次检测日期，临期倒计时
watchEffect(() => {
  let lastestCheckDate = dayjs(2000);
  // 筛选未在编辑的
  const noEditList = ruleForm.parameters.filter(e => !e.isEdit);
  if (noEditList.length <= 0 || !ruleForm.cycle) {
    ruleForm.nextVerifyDate = "";
    ruleForm.countDown = null;
    return;
  }
  noEditList.forEach(item => {
    if (dayjs(item.verifyDate) > lastestCheckDate) {
      lastestCheckDate = dayjs(item.verifyDate);
    }
  });
  lastestCheckDate = dayjs(lastestCheckDate).add(Number(ruleForm.cycle), "day");
  const now = dayjs().startOf("day");
  ruleForm.nextVerifyDate = lastestCheckDate;
  ruleForm.countDown = lastestCheckDate.diff(now, "day");
});

const rules = reactive<FormRules<RuleForm>>({
  deviceName: [{ required: true, message: "请选择设备名", trigger: "change" }],
  deviceAttachName: [{ required: true, message: "请选择设备附件名", trigger: "change" }],
  parameters: [{ required: true, message: "至少添加一条检验信息", trigger: "" }],
  cycle: [{ required: true, message: "请选择设备名", trigger: "change" }]
});

const emits = defineEmits(["submit"]);

const deviceOptions = ref<Array<any>>([]);
const deviceItem = ref<any>({});
const searchLoading = ref(false);
// 设备模糊查询
const remoteMethod = async val => {
  deviceOptions.value = [];
  if (val.toString().length < 1) return;
  searchLoading.value = true;
  const res = await queryEquipLedger({ pageNum: 1, pageSize: 9999, value: val, className: props.className });
  deviceOptions.value = res?.data || [];
  searchLoading.value = false;
};
const deviceNameChange = val => {
  ruleForm.deviceName = val.eqpName;
  ruleForm.deviceCode = val.eqpId;
  ruleForm.deviceStatus = val.eqpRunStatusValue;
  ruleForm.eqpStatus = val.eqpRunStatus;
  ruleForm.manageProperty = val.manageAttr;
};
const getManagePropertyMap = (mp: string) => {
  if (!mp) return "";
  const Map = {
    1: "特种设备",
    2: "计量器具",
    3: "定期检验仪器仪表"
  };
  return mp
    .split(",")
    .map(e => {
      return Map[e];
    })
    .join();
};
const baseDeviceProps = ref([
  {
    label: "设备编码",
    prop: "deviceCode"
  },
  {
    label: "状态",
    prop: "deviceStatus"
  },
  {
    label: "管理属性",
    prop: "manageProperty"
  }
]);
const deviceAttachOptions = ref<Array<any>>([]);
const deviceAttachItem = ref<any>({});
// 设备附件模糊查询
const attachRemoteMethod = async val => {
  deviceAttachOptions.value = [];
  if (val.toString().length < 1) return;
  searchLoading.value = true;
  const res = await queryEquipLedger({ pageNum: 1, pageSize: 9999, value: val, className: props.className });
  deviceAttachOptions.value = res?.data || [];
  searchLoading.value = false;
};
const deviceNameAttachChange = val => {
  // 设备附件新增编辑时候，可以手输入自定义名称，特殊处理
  if (typeof val === "string") {
    ruleForm.deviceAttachName = val;
    ruleForm.deviceAttachCode = "";
  } else {
    ruleForm.deviceAttachName = val.eqpName;
    ruleForm.deviceAttachCode = val.eqpId;
  }
};
const changeDeviceSelect = () => {
  // 回显设备检测数据
  deviceOptions.value = [{ eqpName: ruleForm.deviceName, eqpId: ruleForm.deviceCode }];
  deviceItem.value.eqpName = ruleForm.deviceName;
  deviceItem.value.eqpId = ruleForm.deviceCode;

  // 回显设备附件检测数据
  if (ruleForm.deviceAttachName) {
    deviceAttachOptions.value = [{ eqpName: ruleForm.deviceAttachName, eqpId: ruleForm.deviceAttachCode || "" }];
    deviceAttachItem.value.eqpName = ruleForm.deviceAttachName || "";
    deviceAttachItem.value.eqpId = ruleForm.deviceAttachCode || "";
  }
};
const personOptions = ref<Array<any>>([]);
// 获取责任人的名字
const personChange = val => {
  const arr = personOptions.value.filter(item => {
    return item.value === val;
  });
  if (arr && arr.length > 0) {
    ruleForm.person = arr[0].label;
    ruleForm.personId = arr[0].value;
  }
};
// 责任人获取
const getPserson = async () => {
  personOptions.value = await getEmployeeIdAndName([props.className]);
};

// 获取详情信息
const queryVerifyReportDetailFn = async (id: number) => {
  let params: any = { className: props.className };
  if (props.option.eqpType === "eqp") {
    params.deviceCode = id;
  } else if (props.option.eqpType === "attachment") {
    params.deviceAttachCode = id;
  } else {
    params.id = id;
  }
  const res: any = await queryVerifyReportDetail(params);
  ruleForm.deviceName = res.deviceName;
  ruleForm.deviceStatus = res.deviceStatus;
  ruleForm.eqpStatus = res.eqpStatus;
  ruleForm.deviceCode = res.deviceCode;
  ruleForm.manageProperty = res.manageProperty;
  ruleForm.deviceAttachName = res.deviceAttachName;
  ruleForm.deviceAttachCode = res.deviceAttachCode;
  ruleForm.person = res.person;
  ruleForm.personId = res.personId;
  ruleForm.nextVerifyDate = res.nextVerifyDate;
  ruleForm.reminder = res.reminder;
  ruleForm.cycle = res.cycle;
  ruleForm.files = JSON.parse(res.files);
  ruleForm.parameters = JSON.parse(res.parameters);
  ruleForm.id = res.id;
  changeDeviceSelect();
};
const changeBaseDeviceProps = () => {
  if (props.option.eqpType === "eqp" && props.option.type === "detail") {
    baseDeviceProps.value = [
      {
        label: "状态",
        prop: "deviceStatus"
      }
    ];
  } else if (props.option.eqpType !== "eqp") {
    baseDeviceProps.value = [];
  }
};
onMounted(async () => {
  await getPserson();
  changeBaseDeviceProps();
  if (props.option.type === "add") return;
  queryVerifyReportDetailFn(props.option.data.id);
});
function updateParameters(list: any) {
  ruleForm.parameters = list;
}

const cancelHandler = () => {
  dialogTableVisible.value = false;
};

// 提交
const submitHandler = useThrottleFn(async () => {
  if (!ruleFormRef.value) return;
  const noSureCheckList = ruleForm.parameters.some(e => e.isEdit === true);
  if (noSureCheckList) {
    PxMessage.warning("存在未确认的检测信息！");
    return;
  }
  await ruleFormRef.value.validate(async (valid, fields) => {
    if (valid) {
      loading.value = true;
      const params = {
        ...ruleForm,
        nextVerifyDate: dayjs(ruleForm.nextVerifyDate).format("YYYY-MM-DD"),
        files: JSON.stringify(ruleForm.files),
        parameters: JSON.stringify(
          ruleForm.parameters.map(e => {
            delete e.isEdit;
            return {
              ...e
            };
          })
        ),
        cycle: Number(ruleForm.cycle),
        reminder: Number(ruleForm.reminder)
      };
      if (props.option.type === "add") {
        await insertVerifyReport(params, () => {
          loading.value = false;
        });
      } else if (props.option.type === "edit") {
        await updateVerifyReport(params, () => {
          loading.value = false;
        });
      }
      loading.value = false;
      emits("submit");
      dialogTableVisible.value = false;
    } else {
      console.error("error submit!", fields);
    }
  });
}, delay);
</script>

<style lang="scss" scoped>
:deep(.px-form-item) {
  width: 100%;

  .px-form-item__content {
    .px-input,
    .px-select,
    .px-date-picker,
    .px-time-picker,
    .px-tree-select {
      width: 100%;
    }
  }
}

.custom-label {
  display: flex;
  align-items: center;
  font-weight: 700;
  color: var(--px-text-color-regular);
}

.attachLabel {
  :deep(.px-form-item__label) {
    width: 108px !important;
  }
}
</style>
